package com.example.administrator.nurse.Bluetooth;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Iterator;
import java.util.Set;
import java.util.UUID;

/**
 * Created by 林冠宏 on 2016/4/20.
 *
 *
 */

public class BlueTooth {


    private Context context;

    private static final String TAG = "Bluetooth";

    private static final String MacAddress="00:07:80:BF:98:04";

    private static final UUID MY_UUID=UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); /** 默认 */

    /** 蓝牙设备变量 */
    private BluetoothAdapter mBluetoothAdapter;

    private BluetoothDevice mBluetoothDevice=null;
    private BluetoothSocket mBluetoothSocket;

    public BlueTooth(Context context){
        this.context = context;
    }

    public void init(){
        BluetoothManager bluetoothManager = (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE);
        mBluetoothAdapter = bluetoothManager.getAdapter(); /** sdk 版本限制 */

       // BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();//hhc


        if (mBluetoothAdapter == null){
            Toast.makeText(context,"对不起,您的机器不具备蓝牙功能",Toast.LENGTH_SHORT).show();
            //Toast.m("对不起 ，您的机器不具备蓝牙功能");
            return;
        }
    }

    /** 蓝牙状态广播 */
    public BlueTooth withInfoBroadCast(){
        IntentFilter bluetoothFilter = new IntentFilter();
        bluetoothFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
        bluetoothFilter.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);
        context.registerReceiver(BluetoothRecieverBroadcast, bluetoothFilter);
        return this;
    }

    /** 蓝牙扫描时的广播 */
    public BlueTooth withScanBroadCast(){
        IntentFilter btDiscoveryFilter = new IntentFilter();
        btDiscoveryFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
        btDiscoveryFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        btDiscoveryFilter.addAction(BluetoothDevice.ACTION_FOUND);
        btDiscoveryFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
        context.registerReceiver(BTDiscoveryReceiverBroadcast, btDiscoveryFilter);
        return this;
    }

    public void unRegisterBc(){
        context.unregisterReceiver(BluetoothRecieverBroadcast);
        context.unregisterReceiver(BTDiscoveryReceiverBroadcast);
    }

    /** 打印扫到的蓝牙信息 */
    public void printFoundService(){
        if(mBluetoothAdapter==null){
            Log.d(TAG,"mBluetoothAdapter is null");
            return;
        }
        Set<BluetoothDevice> bts = mBluetoothAdapter.getBondedDevices(); /** 获取已经扫描出了的蓝牙 */
        Iterator<BluetoothDevice> iterator  = bts.iterator();
        while(iterator.hasNext()) {
            BluetoothDevice bd = iterator.next() ;
            Log.i(TAG, " Name : " + bd.getName() + " Address : " + bd.getAddress());
            Log.i(TAG, "Device class" + bd.getBluetoothClass());
        }
    }

    public void open(){
        //if (mBluetoothAdapter.isEnabled())   /** 如果已经打开，直接返回true */
          //  Log.d(TAG,"蓝牙已经打开了");
            //Toast.makeText(context,"蓝牙已经打开了",Toast.LENGTH_SHORT).show();

        if (mBluetoothAdapter.enable()) /** 打开 */
            Toast.makeText(context,"蓝牙打开操作成功",Toast.LENGTH_SHORT).show();
        else
            Toast.makeText(context,"蓝牙打开失败",Toast.LENGTH_SHORT).show();
    }

    public void close(){
        if ( mBluetoothAdapter.disable())
            Toast.makeText(context,"蓝牙关闭操作成功",Toast.LENGTH_SHORT).show();
        else if (!(mBluetoothAdapter.isEnabled()))
            Toast.makeText(context,"蓝牙已经关闭",Toast.LENGTH_SHORT).show();
        else
            Toast.makeText(context,"蓝牙关闭失败",Toast.LENGTH_SHORT).show();
    }

    public void startScan(){
        if (!mBluetoothAdapter.isDiscovering()){
            Log.i(TAG, "btCancelDiscovery ### the bluetooth dont't discovering");
            mBluetoothAdapter.startDiscovery();
        } else
            Toast.makeText(context,"蓝牙正在搜索设备",Toast.LENGTH_SHORT).show();
    }

    public void stopScan(){
        if (mBluetoothAdapter.isDiscovering()){
            Log.i(TAG, "btCancelDiscovery ### the bluetooth is isDiscovering");
            mBluetoothAdapter.cancelDiscovery();
        }
    }

    public void connect(){
        if(mBluetoothSocket.isConnected()) {
            Log.d(TAG, "Name : " + mBluetoothDevice.getName() + " Address: " + mBluetoothDevice.getAddress());
        } else {
            Log.d(TAG, "Connection has been shut down.");
            try {
                connectDevice(mBluetoothDevice);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    public String[] getData() {
        try {
            Log.v(TAG, "****************尝试获取数据****************");
            String str=null;
            Log.v(TAG,"****************Init****************");
            InputStream tempIn = mBluetoothSocket.getInputStream();
            InputStreamReader inputStreamReader=new InputStreamReader(tempIn);
            BufferedReader bufferedReader=new BufferedReader(inputStreamReader);
            if(mBluetoothSocket.isConnected()){
                Log.v(TAG, "****************Getting data****************");
                while((str = bufferedReader.readLine()) != null);
            }
            Log.v(TAG, "****************Finishing Reading****************");
            Log.v("DATA:", str);
            bufferedReader.close();
            inputStreamReader.close();
            tempIn.close();
            return str.split("#");
            //dataDeal(str);

        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    private void connectDevice(BluetoothDevice device) throws IOException {
        mBluetoothSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
        mBluetoothSocket.connect();
    }

    /*public String[] dataDeal(String strings){
        String AirFlow=null;
        String Temperature=null;
        String Pulse=null;
        String Oxygen=null;
        String Conductivity=null;
        String Resistance=null;
        String[] arrayofString=new String (strings).split("#");

        AirFlow=arrayofString[0];
        Temperature=arrayofString[1];
        Pulse=arrayofString[2];
        Oxygen=arrayofString[3];
        Conductivity=arrayofString[4];
        Resistance=arrayofString[5];
        return


    }*/

    /** 蓝牙状态广播接收器 */
    private BroadcastReceiver BluetoothRecieverBroadcast = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub
            if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(intent.getAction())) /** 蓝牙模块被打开或者关闭 */ {
                Log.v(TAG, "蓝牙模块被打开或者关闭");
                int btState = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE,BluetoothAdapter.STATE_OFF);

                printBTState(btState);
            } else if(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED.equals(intent.getAction())) { /** 蓝牙模块扫描模式发生了变化 */
                Log.v(TAG, "蓝牙模块扫描模式发生了变化");
                int cur_mode_state = intent.getIntExtra(BluetoothAdapter.EXTRA_SCAN_MODE, BluetoothAdapter.SCAN_MODE_NONE);
                int previous_mode_state = intent.getIntExtra(BluetoothAdapter.EXTRA_PREVIOUS_SCAN_MODE, BluetoothAdapter.SCAN_MODE_NONE);

                Log.v(TAG, "### cur_mode_state ##" + cur_mode_state + " ~~ previous_mode_state" + previous_mode_state);
                //toast("### cur_mode_state ##" + cur_mode_state + " ~~ previous_mode_state" + previous_mode_state);
            }
        }

    };

    /** 蓝牙扫描时的广播接收器 */
    private BroadcastReceiver BTDiscoveryReceiverBroadcast = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub
            if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(intent.getAction())) { /** 蓝牙适配器开始搜索远程设备 */
                Log.v(TAG, "蓝牙适配器开始搜索远程设备");
            } else if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(intent.getAction())) { /** 蓝牙S适配器完成搜索发出的广播 */
                Log.v(TAG, "蓝牙S适配器完成搜索发出的广播 ");
            } else if(BluetoothDevice.ACTION_FOUND.equals(intent.getAction())) { /** 搜索到蓝牙设备 */
                Log.v(TAG, "搜索到蓝牙设备");

                BluetoothDevice foundedDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

                if(foundedDevice != null) {
                    Log.v(TAG, "Name : " + foundedDevice.getName() + " Address: " + foundedDevice.getAddress());
                    //toast("Name : " + foundedDevice.getName() + " Address: " + foundedDevice.getAddress());
                }
            } else if(BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(intent.getAction())) { /** 蓝牙绑定状态发生改变 */
                Log.v(TAG, "蓝牙绑定状态发生改变");

                int cur_bond_state = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.BOND_NONE);
                int previous_bond_state = intent.getIntExtra(BluetoothDevice.EXTRA_PREVIOUS_BOND_STATE, BluetoothDevice.BOND_NONE);

                Log.v(TAG, "### cur_bond_state ##" + cur_bond_state + " ~~ previous_bond_state" + previous_bond_state);
                //toast("### cur_bond_state ##" + cur_bond_state + " ~~ previous_bond_state" + previous_bond_state);
            }
        }
    };

    private void printBTState(int btState) {
        switch (btState) {
            case BluetoothAdapter.STATE_OFF:
                //toast("蓝牙状态:已关闭");
                Log.v(TAG, "BT State ： 已关闭");
                break;
            case BluetoothAdapter.STATE_TURNING_OFF:
                //toast("蓝牙状态:正在关闭");
                Log.v(TAG, "BT State :  正在关闭");
                break;
            case BluetoothAdapter.STATE_TURNING_ON:
                //toast("蓝牙状态:正在打开");
                Log.v(TAG, "BT State ：正在打开");
                break;
            case BluetoothAdapter.STATE_ON:
                //toast("蓝牙状态:已打开");
                Log.v(TAG, "BT State ：已打开");
                break;
            default:
                break;
        }
    }


}
